package com.yxuan.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.yxuan.springboot.WxPayUtil.HttpUtils;
import com.yxuan.springboot.WxPayUtil.WeChatBasePayData;
import com.yxuan.springboot.WxPayUtil.WxNotifyType;
import com.yxuan.springboot.WxPayUtil.WxPayCommon;
import com.yxuan.springboot.constant.SystemConstant;
import com.yxuan.springboot.constant.config.WxPayConfig;
import com.yxuan.springboot.constant.config.WxPayConfigForAC;
import com.yxuan.springboot.model.*;
import com.yxuan.springboot.service.OrdersService;
import com.yxuan.springboot.service.UserInformationService;
import com.yxuan.springboot.service.UserVipService;
import com.yxuan.springboot.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yxuan.springboot.service.AcuserLoginService;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.yxuan.springboot.util.Code.SUCCESSCODE;

/**
 *
 * @author zchao
 *    AcuserLogin业务层实现类
 * @date 2024-05-16 18:10:48
 */
@Slf4j
@Service
@Transactional
public class AcuserLoginServiceImpl extends BaseServiceImpl<AcuserLogin> implements AcuserLoginService {

    private String APP_ID = "wx192f019efa82b221";
    private String APP_SECRET = "8457a376f542b38eb62a22f403f77862";

    @Autowired
    private AcuserLoginService acuserLoginService;
    @Autowired
    private UserVipService userVipService;
    @Autowired
    private UserInformationService userInformationService;
    @Autowired
    private OrdersService ordersService;
    @Resource
    private WxPayConfigForAC wxPayConfigForAC;
    @Resource(name = "wxPayClientAC")
    private CloseableHttpClient wxPayClientAC;

    @Autowired
    private WxPayUtilForAC wxPayUtil;

    @Override
    public Result wxlogin(String code) throws Exception {
        try {
            log.info("code:" + code);
            //String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";

            log.info("url:" + url);
            String result = HttpUtils.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("获取到的微信登录回调结果" + jsonObject.toJSONString());
            String accessToken = jsonObject.getString("access_token");
            String openId = jsonObject.getString("openid");
            AcuserLogin userLogin = new AcuserLogin();
            userLogin.setOpenid(openId);
            log.info("openid:" + openId);
            if(openId.isEmpty()||openId==null){
                return new Result(201,"openid为空");
            }
            //根据phoneNumber查询用户是否存在，存在就将openid进去，不在就创建新用户
            //根据openid查询用户是否存在，不在就创建新用户
            AcuserLogin userLoginPho = new AcuserLogin();
            userLoginPho.setOpenid(openId);
            AcuserLogin targetPho = acuserLoginService.findObjectByPramas(userLoginPho);
            if (targetPho == null) {
                log.info("用户不存在，执行注册");
                //若不存在则自动创建该用户（即自动注册）
                //设置当前添加的时间
                Date date = new Date(System.currentTimeMillis());
                SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                Date AppliedTime = formatter.parse(formatter.format(date));
                userLogin.setEndTime(AppliedTime);
                userLogin.setOpenid(openId);
                String pho = IdUtil.generateUniqueId();
                userLogin.setPhoneNumber(pho);
                int userId = IdUtil.getIntUserId();
                userLogin.setUserId(userId);
                log.info("添加用户");
                acuserLoginService.save(userLogin);

                UserVip userVip = new UserVip();
                // userVip.setDeleted("0");
                userVip.setUserId(userId);
                userVip.setVipRank("0");
                userVip.setCourseSelectionTimes("0");
                userVip.setFillingTimes("0");
                userVip.setProbabilityTimes("1");
                userVip.setTimeBuying(AppliedTime);
                userVip.setInfoUpdTimes("1");
                userVip.setGptTimes("3");
                log.info("添加vip数据");
                userVipService.save(userVip);

                //设置userInformation默认值
                UserInformation userInformation = new UserInformation();
                userInformation.setUserId(userId);
                userInformation.setHeadImage("https://editor-md-1317285847.cos.ap-beijing.myqcloud.com/null/260191685253771311.png");
                userInformation.setUserName("用户" + userLogin.getPhoneNumber().substring(userLogin.getPhoneNumber().length() - 5));
                userInformation.setPhoneNumber(pho);
                userInformation.setVipRank("0");
                Date date1 = DaysCalculateUtil.targetDate(AppliedTime, 0, 0, -1);
                userInformation.setUpdTime(date1);
                log.info("添加用户默认信息");
                userInformationService.save(userInformation);

                Map<Object, Object> map = new HashMap<>();
                map.put("userId", userId);
                map.put("openId",openId);
                return new Result(map, SUCCESSCODE, "登录/注册成功");
            }

            //用户存在，直接修改token
            AcuserLogin login1 = new AcuserLogin();
            login1.setId(targetPho.getId());
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date AppliedTime = formatter.parse(formatter.format(date));
            login1.setEndTime(AppliedTime);
            acuserLoginService.upd(login1);

            Map<Object, Object> map = new HashMap<>();
            map.put("userId", targetPho.getUserId());
            map.put("openId",openId);
            return new Result(map, SUCCESSCODE, "登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(201, "登录/注册失败");
        }
    }

    @Override
    public Result ACJsApiPay(String orderId, String openid) throws Exception {

        //根据订单号查询订单信息，给基础数据设置基础值
        Orders orders = new Orders();
        orders.setOrderId(orderId);
        Orders targetOrder = ordersService.findObjectByPramas(orders);

        WeChatBasePayData weChatBasePayData = new WeChatBasePayData();
        weChatBasePayData.setTitle(targetOrder.getName());
        weChatBasePayData.setOrderId(targetOrder.getOrderId());
//        String total = targetOrder.getTotal();
//        int i = Integer.parseInt(total);
        weChatBasePayData.setPrice(targetOrder.getTotal());
        //设置回调地址
        weChatBasePayData.setNotify(WxNotifyType.JSAPI_NOTIFY2);
        HashMap<String, Object> map = new HashMap<>();
        log.info("接收pre");
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppid(wxPayConfigForAC.getAppid());
        wxPayConfig.setMchSerialNo(wxPayConfigForAC.getMchSerialNo());
        wxPayConfig.setPrivateKeyPath(wxPayConfigForAC.getPrivateKeyPath());
        wxPayConfig.setMchId(wxPayConfigForAC.getMchId());
        wxPayConfig.setKey(wxPayConfigForAC.getKey());
        wxPayConfig.setDomain(wxPayConfigForAC.getDomain());
        wxPayConfig.setNotifyDomain(wxPayConfigForAC.getNotifyDomain());
        String prepay_id = WxPayCommon.wxJsApiPay(wxPayConfig, weChatBasePayData, openid, wxPayClientAC);
        map.put("package","prepay_id="+prepay_id);
        //时间戳
        long timestamp = System.currentTimeMillis()/1000;
        //随机串
        String nonceStr = java.util.UUID.randomUUID().toString().replace("-","");
        String pck = "prepay_id="+prepay_id;

        String pckSign = wxPayUtil.getSign(wxPayConfig.getAppid(),timestamp,nonceStr,pck);

        String time = String.valueOf(timestamp);
        map.put("timestamp",time);
        map.put("nonceStr",nonceStr);
        map.put("signType","RSA");
        map.put("paySign",pckSign);
        map.put("appid",wxPayConfig.getAppid());
        map.put("partnerid",wxPayConfig.getMchId());

        return new Result(map, 200, "订单请求发送成功");


    }


}
